/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.com.insejeccg.util.bean.convert;

import br.com.insejeccg.util.bean.formatter.Formatter;


@SuppressWarnings("unchecked")
public class DecimalConverter implements ConverterToString {
    private Object defaultValue;

    public DecimalConverter(String keyPattern, Object defaultValue) {
        super();
        this.defaultValue = defaultValue;
    }

	public Object convert(Class type, Object value) {
        if (value == null) {
            return (defaultValue);
        }

        if (type.isInstance(value)) {
            return value;
        }

        try {
            Object resp = defaultValue;

            Number number = null;

            if (value instanceof Number) {
                number = (Number) value;
            } else {
                number = (Number)Formatter.parseDecimal(value.toString());
            }

            if (type.equals(Double.class)) {
                resp = new Double(number.doubleValue());
            } else if (type.equals(Float.class)) {
                resp = new Float(number.floatValue());
            }

            return resp;
        } catch (Exception e) {
            return (defaultValue);
        }
    }

    public String convertToString(Object value) {
        if ((value != null) && value instanceof Number) {
            try {
                return Formatter.format((Number)value);
            } catch (Exception e) {
                return "";
            }
        }

        return "";
    }

  
}
